#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <fstream>
#include <sstream>
#include <math.h>
#include "../../resource/data/faces/face.hpp"

using namespace std;
using namespace cv;

RNG g_rng(12345);
Ptr<face::FaceRecognizer> model;
const cv::Size imgRawSize(640, 480);

int facePredict(const Mat& src_image)  //识别图片
{
    Mat face_test;
    int predict = 0;
    //截取的ROI人脸尺寸调整
//    if (src_image.rows >= 120)
//    {
        //改变图像大小，使用双线性差值
        resize(src_image, face_test, Size(92, 112));
//    }
    //判断是否正确检测ROI
    if (!face_test.empty())
    {
        //测试图像应该是灰度图
        predict = model->predict(face_test);
    }
    cout << predict << endl;
    return predict;
}



int main()
{
    VideoCapture cap(0);    //打开默认摄像头
    if (!cap.isOpened())
    {
        return -1;
    }
    int scale = 2;
    Mat frame, gray;
    Mat smallImg( imgRawSize/scale, CV_8UC1 );
    int detectResult = 0;
    string faceName;
    vector<Rect> faces;//建立用于存放人脸的向量容器
    //这个分类器是人脸检测所用
    CascadeClassifier cascade;
    cascade.load("../../resource/data/faces/haarcascades/haarcascade_frontalface_alt2.xml");
    model = face::EigenFaceRecognizer::create();
    //1.加载训练好的模型
    model->read("../../resource/data/faces/model/MyFacePCAModel.xml");
    while (1)
    {
        cap >> frame;
        //对图片进行缩小
        cvtColor(frame, gray, CV_RGB2GRAY);//测试图像必须为灰度图
        //缩小图像
        resize( gray, smallImg, smallImg.size(), 0, 0, INTER_LINEAR );
        equalizeHist(smallImg, smallImg); //变换后的图像进行直方图均值化处理
        //检测人脸
        cascade.detectMultiScale(smallImg, faces,
            1.1, 4, 0
            //|CV_HAAR_FIND_BIGGEST_OBJECT
            | CV_HAAR_DO_ROUGH_SEARCH
            //| CV_HAAR_SCALE_IMAGE,
                                 );
        //框出人脸
        for (size_t i = 0; i < faces.size(); i++)
        {
            Mat faceROI = gray(faces[i]); //将所有的脸部保存起来
            if (faceROI.empty())
                continue;
            detectResult = facePredict(faceROI);
            switch (detectResult) //对每张脸都识别
            {
                case 0:faceName = "BelingBeling"; break;
                default: faceName = "Error"; break;
            }
            cv::Scalar color(255, 0, 0);
            //将图像按比例缩放回去
            rectangle( frame, Point(cvRound(faces[i].x*scale), cvRound(faces[i].y*scale)),
                       Point(cvRound((faces[i].x + faces[i].width-1)*scale), cvRound((faces[i].y + faces[i].height-1)*scale)),
                       color, 3, 8, 0);
            putText(frame, faceName, faces[i].tl()*scale, FONT_HERSHEY_COMPLEX, 1, Scalar(0, 0, 255));//添加文字
        }

        imshow("face", frame);
        waitKey(10);
    }

    return 0;
}
